package com.sauro.common.util;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 文章参考 ：https://mp.weixin.qq.com/s/bgOBatfb__c2XVQm8hd7Kw
 * 微信公众号：IT老哥 (一次订单号重复引起的事故，把我坑惨了！)
 */
public class OrderNumber {
    /**
     * 订单号生成(NEW)
     **/
    private static final AtomicInteger SEQ = new AtomicInteger(1000);
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyMMddHHmmssSS");
    private static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");

    public static String generateOrderNo() {
        LocalDateTime dataTime = LocalDateTime.now(ZONE_ID);
        if (SEQ.intValue() > 9990) {
            SEQ.getAndSet(1000);
        }
        return dataTime.format(DF_FMT_PREFIX) + SEQ.getAndIncrement();
    }

    public static void main(String[] args) {
        // 使用
//        String s = OrderNumber.generateOrderNo();
//        System.out.println(s);
        System.out.println("Test.generateOrderNo() = " + OrderNumber.generateOrderNo());

        // 测试是否生成重复订单号
//         List<String> orderNos = Collections.synchronizedList(new ArrayList<String>());
//         IntStream.range(0,11000).parallel().forEach(i->{
//             orderNos.add(generateOrderNo());
//         });
//
//         List<String> filterOrderNos = orderNos.stream().distinct().collect(Collectors.toList());
//         System.out.println("orderNos = " + orderNos);
//         System.out.println("生成订单数："+orderNos.size());
//         System.out.println("过滤重复后订单数："+filterOrderNos.size());
//         System.out.println("重复订单数："+(orderNos.size()-filterOrderNos.size()));
    }


}
